import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './useUserStore'
import { addCart, getCart, delCart } from '@/apis/getCart'

export const useCarStore = defineStore(
  'car',
  () => {
    const userStore = useUserStore()

    const loginState = computed(() => userStore.userStore.token)
    const carList = ref([])

    const updateCar = async () => {
      const res = await getCart()
      carList.value = res.result
    }
    // 判断添加商品
    const getAddCar = async (data) => {
      const { skuId, count } = data
      if (loginState.value) {
        await addCart({ skuId, count })
        updateCar()
      } else {
        const good = carList.value.find((item) => item.skuId === data.skuId)
        if (good) {
          good.count += data.count
        } else {
          carList.value.push(data)
        }
      }
    }

    // 删除商品
    const getDelCart = async (id) => {
      if (loginState.value) {
        await delCart([id])
        updateCar()
      } else {
        carList.value = carList.value.filter((item) => item.skuId !== id)
      }
    }

    // 计算商品
    const allCount = computed(() => carList.value.reduce((all, item) => all + item.count, 0))
    const allPrice = computed(() => carList.value.reduce((all, item) => all + item.count * item.price, 0))
    const carCount = computed(() => carList.value.filter((item) => item.selected).reduce((all, item) => all + item.count, 0))
    const carPrice = computed(() => carList.value.filter((item) => item.selected).reduce((all, item) => all + item.count * item.price, 0))

    // 设置购物车选中状态
    const stateChange = (id, state) => {
      const list = carList.value.find((item) => item.skuId === id)
      list.selected = state
    }

    // 设置全选
    const allState = computed(() => carList.value.every((item) => item.selected))
    const checkChange = (state) => carList.value.forEach((item) => (item.selected = state))

    // 清除信息
    const clearCar = () => (carList.value = {})

    return {
      carList,
      allCount,
      allPrice,
      allState,
      carCount,
      carPrice,
      clearCar,
      getAddCar,
      getDelCart,
      stateChange,
      checkChange,
      updateCar,
    }
  },
  {
    persist: true,
  }
)
